//
//  YPATSelectViewController.m
//  ChengHuiTong
//
//  Created by xzm on 16/8/5.
//  Copyright © 2016年 张文权. All rights reserved.
//

#import "YPATSelectViewController.h"
#import "UIView+DatePicker.h"
#import "NSDate+Extension.h"
#import "TypesetBtnList.h"
#define ATSelectLeftSpace 12
#define ATSelectBtnSpace 5
#define ATSelectVSpace 10

typedef NS_ENUM(NSInteger, UITextFieldType) {
    UITextFieldFirstMoney,
    UITextFieldLastMoney,
    UITextFieldFirstTime,
    UITextFieldLastTime
};

@interface ATSTextField : UITextField

@property (nonatomic,assign)UITextFieldType type;

@end

@implementation ATSTextField

@end

@interface YPATSelectViewController ()<UITextFieldDelegate,clickDelegate>{
    
    YPautoEditBin *_selectModel;
    
    UIView*_warnView;
    
    NSDictionary *_limitDic; //借款期限
    NSDictionary *_borrowStyleDic; //还款方式
    NSDictionary *_borrowTypeDic; //标种类型
    NSDictionary *_enabledDic; //生效方式
    
    TypesetBtnList *_limitBtnListView; //借款期限
    TypesetBtnList *_styleBtnListView; //还款方式
}

@end

@implementation YPATSelectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpUI];
}

- (void)setUpUI{
    
    self.view.backgroundColor = UIColorFromString(@"#f6f6f6");
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.title = @"自动投标";
    
    if (self.model) {
        
        
        _selectModel=self.model;
        
        
        _selectModel.sort=nil;
                
        _selectModel.token=[YPShareAccountInfo shareAccountInfo].token;
        
        
    }else{
        
        
        _selectModel = [[YPautoEditBin alloc]init];
        
        _selectModel.token=[YPShareAccountInfo shareAccountInfo].token;
        
        _selectModel.timelimit=@"-1";
        
        _selectModel.borrow_style=@"-1";
        
        _selectModel.borrow_type=@"-1";
        
        _selectModel.enabled=@"-1";
        
        _selectModel.borrow_trust=[NSString stringWithFormat:@"%@",[NSNumber numberWithBool:self.isTrust]];
    }
    
   

       
 
   
    
    [self creatAllView];
    
   
}

-(void)creatAllView{
    
    
    _limitDic=@{
                @"1":@"1个月",
                @"3":@"3个月",
                @"6":@"6个月",
                @"12":@"12个月",
                @"18":@"18个月",
                @"24":@"24个月",
                @"36":@"36个月",
                };
    _borrowStyleDic=@{
                        @"1":@"全部",
                        @"3":@"先息后本",
                        @"0":@"等额本息",
                        @"4":@"等额本金"
                        };
    _borrowTypeDic=@{
                    @"0":@"全部",
                    @"1":@"诚信贷",
                    @"2":@"诚车贷",
                    @"5":@"加信贷"
                    };
    _enabledDic=@{
                    @"1":@"是",
                    @"0":@"否",
                };
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissKB)];
    
    [self.view addGestureRecognizer:tap];
    
    
    UIView *moneyView = [self textFieldViewWithTitle:@"投标金额:" textFieldTypeOne:UITextFieldFirstMoney typeTow:UITextFieldLastMoney];
    
    moneyView.top = 20;
    
    moneyView.left = ATSelectLeftSpace;
    
    [self.view addSubview:moneyView];
    
    
    
    UIView*timeList=[self btnSelectViewWithTitle:@"借款期限"
                                       btnTitles:@[@"1个月",@"3个月",@"6个月",@"12个月",@"18个月",@"24个月",@"36个月"]
                                   defaultChoice:[_limitDic valueForKey:_selectModel.timelimit]];
    
    timeList.top=moneyView.bottom+10;
    
    [self.view addSubview:timeList];
    
    
    UIView*moneyBackStyle=[self btnSelectViewWithTitle:@"还款方式"
                                             btnTitles:@[@"全部",@"先息后本",@"等额本息",@"等额本金"]
                                         defaultChoice:[_borrowStyleDic valueForKey:_selectModel.borrow_style]];
    
    moneyBackStyle.top=timeList.bottom+10;
    
    [self.view addSubview:moneyBackStyle];
    
    UIView*projectStyle=[self btnSelectViewWithTitle:@"标种类型"
                                           btnTitles:@[@"全部",@"诚信贷",@"诚车贷",@"加信贷"]
                                       defaultChoice:[_borrowTypeDic valueForKey:_selectModel.borrow_type]];
    
    projectStyle.top=moneyBackStyle.bottom+10;
    
    [self.view addSubview:projectStyle];
    
    UIView*canUse=[self btnSelectViewWithTitle:@"生效方式"
                                     btnTitles:@[@"是",@"否"]
                                 defaultChoice:[_enabledDic valueForKey:_selectModel.enabled]];
    
    canUse.top=projectStyle.bottom+10;
    
    [self.view addSubview:canUse];
    
    UIView *timeView = [self textFieldViewWithTitle:@"生效时间:"
                                   textFieldTypeOne:UITextFieldFirstTime
                                            typeTow:UITextFieldLastTime];
    
    
    timeView.top = canUse.bottom + ATSelectVSpace;
    
    timeView.left = ATSelectLeftSpace;
    
    [self.view addSubview:timeView];
    
    UIButton*updateButton=[UIButton buttonWithType:UIButtonTypeCustom];
    
    updateButton.frame=CGRectMake(50, 0, SCREEN_WIDTH-100, 35);
    
    if (_model) {
        
        [updateButton setTitle:@"修改自动投标" forState:UIControlStateNormal];
        
    }else{
        
        [updateButton setTitle:@"添加自动投标" forState:UIControlStateNormal];
    }
    
    
    
    [updateButton setBackgroundColor:kColor_AppNavColor];
    
    [updateButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [updateButton addTarget:self action:@selector(updateData) forControlEvents:UIControlEventTouchUpInside];
    
    
    updateButton.top=timeView.bottom+20;
    
    [self.view addSubview:updateButton];
    
    
    
}

#pragma mark -- 事件响应

-(void)updateData{
    
    
    if (_selectModel.min_account.length==0||_selectModel.tender_account.length==0) {
        
        [MBProgressHUD showError:@"请输入有效的投资金额" toView:self.view];
        
        return;

        
    }
    if (![self isPureFloat:_selectModel.min_account]||![self isPureFloat:_selectModel.tender_account]) {
        
        
        [MBProgressHUD showError:@"请输入有效的投资金额" toView:self.view];
        
        return;
    }
    if ([_selectModel.min_account floatValue] < 50) {
        
        [MBProgressHUD showError:@"最低投标金额为50元" toView:self.view];
        
        return;
    }
    if ([_selectModel.tender_account doubleValue]<[_selectModel.min_account doubleValue]) {
        
        
        [MBProgressHUD showError:@"最大投资金额不能小于最小投资金额" toView:self.view];
        
        return;
        
    }else{
        
        
    }
//    _selectModel.timelimit=@"-1";
//    
//    _selectModel.borrow_style=@"-1";
//    
//    _selectModel.borrow_type=@"-1";
//    
//    _selectModel.enabled=@"-1";
    
    if ([_selectModel.timelimit isEqualToString:@"-1"]) {
        [MBProgressHUD showError:@"请选择借款期限" toView:self.view];
        return;
        
    }
    if ([_selectModel.borrow_style isEqualToString:@"-1"]) {
        [MBProgressHUD showError:@"请选择还款方式" toView:self.view];
        return;
    }
    if ([_selectModel.borrow_type isEqualToString:@"-1"]) {
        [MBProgressHUD showError:@"请选择标种类型" toView:self.view];
        return;
    }
    if ([_selectModel.enabled isEqualToString:@"-1"]) {
        [MBProgressHUD showError:@"请选择生效方式" toView:self.view];
        return;
    }
    
    
    if (_selectModel.validity_start.length==0||_selectModel.validity_end.length==0) {
        
        [MBProgressHUD showError:@"请输入有效的投资时间" toView:self.view];
        
        return;
        
        
    }

    if ([NSDate getTimeWith:_selectModel.validity_end fomatter:@"yyy-MM-dd"]<
        [NSDate getTimeWith:_selectModel.validity_start fomatter:@"yyy-MM-dd"]) {
        
        
        [MBProgressHUD showError:@"投标结束时间不能在投标开始时间之前" toView:self.view];
        
        return;
    }
    
   
    
    
    if (_model) {
    [YPHttpRequestMethod updateRequestURL:autoEdit withData:[_selectModel dictionaryValue] withCompletionBlock:^(NSDictionary *responseDictionary) {
        
        
        if ([responseDictionary[@"status"] intValue]==0) {
            
            if (self.getNewData) {
                
                self.getNewData();
            }
            
            [self.navigationController popViewControllerAnimated:YES];

            
        }else if ([responseDictionary[@"status"] intValue]==1409){
            
            [MBProgressHUD showError:@"每种期限类型最多只能添加2个自动投标" toView:self.view];
            
        }else if ([responseDictionary[@"status"] intValue]==1408){
            
            [MBProgressHUD showError:@"投标金额设置错误" toView:self.view];
        }

        
        
    } withFailedBlock:^(NSError *error) {
        
    } withIndicator:YES atView:self.view];
        
        
    }else{
        
        [YPHttpRequestMethod updateRequestURL:autoAdd withData:[_selectModel dictionaryValue] withCompletionBlock:^(NSDictionary *responseDictionary) {
            if ([responseDictionary[@"status"] intValue]==0) {
                
                
                [self.navigationController popViewControllerAnimated:YES];
            }else if ([responseDictionary[@"status"] intValue]==1409){
                
                [MBProgressHUD showError:@"每种期限类型最多只能添加2个自动投标" toView:self.view];
            }else if ([responseDictionary[@"status"] intValue]==1408){
                
                [MBProgressHUD showError:@"投标金额设置错误" toView:self.view];
            }
            
            
        } withFailedBlock:^(NSError *error) {
            
        } withIndicator:YES atView:self.view];
        
    }
    
}

-(void)clickWithTitle:(NSString *)title  Btn:(UIButton *)btn typeListTitle:(NSString*)list btnListView:(TypesetBtnList *)btnListView{
    
    NSLog(@"%@----%@",title,list);
    
    if ([list isEqualToString:@"借款期限"]) {
        
//        //18个月跟24个月只能是加信贷或者诚信贷
//        if (([title isEqualToString:@"18个月"] || [title isEqualToString:@"24个月"]|| [title isEqualToString:@"36个月"]) && !([_selectModel.borrow_type isEqualToString:@"5"] || [_selectModel.borrow_type isEqualToString:@"1"] || [_selectModel.borrow_type isEqualToString:@"-1"])) {
//            btnListView.defaultChoice = [_limitDic valueForKey:_selectModel.timelimit];
//            [MBProgressHUD showError:[NSString stringWithFormat:@"%@标种类型只能为加信贷或诚信贷",title] toView:self.view];
//            return;
//        }
        
        _selectModel.timelimit= [self keyForValue:title dic:_limitDic];
        
    }
    
    
    if ([list isEqualToString:@"还款方式"]) {
        
        //选择的是等额本金，且标种类型不是家信贷或者没有选择的时候，则return
        if ([title isEqualToString:@"等额本金"] && !([_selectModel.borrow_type isEqualToString:@"5"] || [_selectModel.borrow_type isEqualToString:@"-1"])) {
            btnListView.defaultChoice = [_borrowStyleDic valueForKey:_selectModel.borrow_style];
            [MBProgressHUD showError:@"等额本金时标种类型只能为加信贷" toView:self.view];
            return;
        }
        _selectModel.borrow_style=[self keyForValue:title dic:_borrowStyleDic];

    }
    
    if ([list isEqualToString:@"标种类型"]) {
        
        _selectModel.borrow_type=[self keyForValue:title dic:_borrowTypeDic];
        
//        //选择的不是家信贷或者诚信贷，且期限为18/24/36，将期限还原
//        if (!([title isEqualToString:@"加信贷"] || [title isEqualToString:@"诚信贷"]) && ([_selectModel.timelimit isEqualToString:@"18"] || [_selectModel.timelimit isEqualToString:@"24"] || [_selectModel.timelimit isEqualToString:@"36"])) {
//            
//            //将借款期限还原至默认
//            _selectModel.timelimit = @"1";
//            _limitBtnListView.defaultChoice = [_limitDic valueForKey:_selectModel.timelimit];
//            
//        }
        
        if (![title isEqualToString:@"加信贷"] && [_selectModel.borrow_style isEqualToString:@"4"]) {
            
            //将还款类型还原
            _selectModel.borrow_style = @"1";
            _styleBtnListView.defaultChoice = [_borrowStyleDic valueForKey:_selectModel.borrow_style];
        }
    }
    
    if ([list isEqualToString:@"生效方式"]) {
        
        _selectModel.enabled=[self keyForValue:title dic:_enabledDic];
    }
    
    
    
}

- (BOOL)textFieldShouldBeginEditing:(ATSTextField *)textField{
    
    if (textField.type == UITextFieldFirstTime) {
        
        [self.view endEditing:YES];
        
        
        [self.view showDatePickerWith:[NSDate getDateWithString:_selectModel.validity_start fomatter:@"yyyy-MM-dd"] FinishBlock:^(NSDate *date) {
            
            _selectModel.validity_start = [NSDate getDateStringWithDate:date fomatter:@"yyyy-MM-dd"];
            
            textField.text = _selectModel.validity_start;
        }];
       
        return NO;
        
    }else if (textField.type == UITextFieldLastTime){
        
        [self.view endEditing:YES];
        
        
        [self.view showDatePickerWith:[NSDate getDateWithString:_selectModel.validity_end fomatter:@"yyyy-MM-dd"] FinishBlock:^(NSDate *date) {
            
            _selectModel.validity_end = [NSDate getDateStringWithDate:date fomatter:@"yyyy-MM-dd"];
            
            textField.text = _selectModel.validity_end;

        }];
               return NO;
    }
    
    return YES;
}

- (void)textFieldDidEndEditing:(ATSTextField *)textField{
    
    if (textField.type == UITextFieldFirstMoney) {
        
        _selectModel.min_account = textField.text;
        
    }else if (textField.type == UITextFieldLastMoney){
        
        _selectModel.tender_account = textField.text;
        
    }
}

#define myDotNumbers     @"0123456789.\n"
#define myNumbers          @"0123456789\n"
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if ([string isEqualToString:@"\n"]||[string isEqualToString:@""]) {//按下return
        return YES;
    }
    
    
    NSCharacterSet *cs;
    NSUInteger nDotLoc = [textField.text rangeOfString:@"."].location;
    if (NSNotFound == nDotLoc && 0 != range.location) { //无小数点的情况
        cs = [[NSCharacterSet characterSetWithCharactersInString:myNumbers]invertedSet];
        if ([string isEqualToString:@"."]) {
            return YES;
        }
        if (textField.text.length>8) {  //小数点前面8位
            return NO;
        }
    }
    else { //有小数点的情况
        cs = [[NSCharacterSet characterSetWithCharactersInString:myDotNumbers]invertedSet];
        if (textField.text.length>=13 || [string isEqualToString:@"."]) {
            return  NO;
        }
        
    }
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basicTest = [string isEqualToString:filtered];
    if (!basicTest) {
        return NO;
    }
    if (NSNotFound != nDotLoc && range.location > nDotLoc +2) {//小数点后面两位
        return NO;
    }
    return YES;
}

- (UIView *)btnSelectViewWithTitle:(NSString *)title btnTitles:(NSArray *)btnTitles defaultChoice:(NSString*)defaultChoice{
    
    float height=((btnTitles.count+2)/3)*34;
    
    UIView*view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
    
    UILabel*label=[[UILabel alloc] initWithFrame:CGRectMake(12, 8, 60, 15)];
    
    label.text=[NSString stringWithFormat:@"%@:",title];
    
    label.font=[UIFont systemFontOfSize:12];
    
    label.textColor= UIColorFromString(@"#666666");
    
    [view addSubview:label];
    
    TypesetBtnList*buttonList = [[TypesetBtnList alloc]initWithFrame:CGRectMake(label.right, 0, SCREEN_WIDTH-label.right, height)];
    
    buttonList.defaultChoice=defaultChoice;
    
    [buttonList setBoedercolorWith:UIColorFromString(@"#bbbbbb")];
    
    buttonList.listTitle=title;
    
    buttonList.titleColor=UIColorFromString(@"#bbbbbb");
    
    [buttonList setTags:btnTitles];
    
    [buttonList setLabelBackgroundColor:UIColorFromString(@"#ffffff")];
    
    [buttonList fittedSize];
    
    buttonList.delegate=self;
    
    if ([title isEqualToString:@"借款期限"]) {
        _limitBtnListView = buttonList;
    }else if ([title isEqualToString:@"还款方式"]){
        
        _styleBtnListView = buttonList;
    }
    
    [view addSubview:buttonList];
    
    return view;
}

- (UIView *)textFieldViewWithTitle:(NSString *)title textFieldTypeOne:(UITextFieldType)typeOne typeTow:(UITextFieldType)typeTow{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - ATSelectLeftSpace*2, 20)];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 60, 30)];
    label.text = title;
    label.font = [UIFont systemFontOfSize:12];
    label.textColor = UIColorFromString(@"#666666");
    [view addSubview:label];
    
    CGFloat middleLabelWidth = 20;
    CGFloat tfWidth = (view.width - label.width - middleLabelWidth)/2;
    
    ATSTextField *textFieldOne = [self creatTextFieldWithFrame:CGRectMake(label.right, 0, tfWidth, label.height) type:typeOne font:label.font];
    [view addSubview:textFieldOne];
    
    UILabel *middleLabel = [[UILabel alloc]initWithFrame:CGRectMake(textFieldOne.right, 0, middleLabelWidth, label.height)];
    middleLabel.textAlignment = NSTextAlignmentCenter;
    middleLabel.text = @"-";
    middleLabel.font = [UIFont systemFontOfSize:12];
    middleLabel.textColor = UIColorFromString(@"#7C7C7C");
    [view addSubview:middleLabel];
    
    ATSTextField *textFieldTwo = [self creatTextFieldWithFrame:CGRectMake(middleLabel.right, 0, tfWidth, textFieldOne.height) type:typeTow font:label.font];
    
    [view addSubview:textFieldTwo];
    
    view.height = textFieldTwo.bottom;
    
    if (typeOne == UITextFieldFirstMoney) {
        
        textFieldOne.placeholder=@"最低投资额";
        
        
    }
    if (typeTow == UITextFieldLastMoney){
        
        textFieldTwo.placeholder=@"最高投资额";
        
    }

    if (typeOne == UITextFieldFirstTime) {
        
        textFieldOne.placeholder=@"开始时间";
        
        
    }
    if (typeTow == UITextFieldLastTime){
        
        textFieldTwo.placeholder=@"结束时间";
        
    }
    
    if (self.model) {
        
        
        if (typeOne == UITextFieldFirstMoney) {
            
            textFieldOne.text=_selectModel.min_account;
            
        }else if (typeOne == UITextFieldFirstTime){
            
            
            
            textFieldOne.text=_selectModel.validity_start;
            
        }
        
        if (typeTow == UITextFieldLastMoney) {
            
            textFieldTwo.text=_selectModel.tender_account;
            
        }else if (typeTow == UITextFieldLastTime){
            
            textFieldTwo.text=_selectModel.validity_end;
            
        }

        
    }
    
    return view;
}

- (ATSTextField *)creatTextFieldWithFrame:(CGRect)frame type:(UITextFieldType)type font:(UIFont *)font{
    
    
    
    ATSTextField *textField = [[ATSTextField alloc]initWithFrame:frame];
    textField.textAlignment = NSTextAlignmentCenter;
    textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    textField.textColor = UIColorFromString(@"#7C7C7C");
    textField.font = font;
    textField.type = type;
    textField.textAlignment = NSTextAlignmentCenter;
    textField.delegate = self;
    textField.layer.borderColor = ColorWithRGB(220, 220, 220).CGColor;
    textField.layer.borderWidth = 1;
    
    return textField;
}

- (BOOL)isPureFloat:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return [scan scanFloat:&val] && [scan isAtEnd];
}

- (void)dismissKB{
    
    [self.view endEditing:YES];
}

/**通过字典value找key*/
- (NSString *)keyForValue:(NSString *)value dic:(NSDictionary *)dic{
    
    __block NSString *keys = @"";
    [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSLog(@"%@==%@===%@",key,obj,value);
        if ([obj isEqualToString:value]) {
            
            keys = (NSString *)key;
            *stop = YES;
            
        }
    }];
    
    return keys;
}

@end
